home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11046 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: dawn.mmm.com!news
  2. From: kjhopps@mmm.com (Kevin J Hopps)
  3. Newsgroups: comp.lang.c++,rb.technical
  4. Subject: Re: Can copy constructor and operator= share code?
  5. Followup-To: comp.lang.c++,rb.technical
  6. Date: 12 Mar 1996 14:21:12 GMT
  7. Organization: 3M - St. Paul, MN  55144-1000 US
  8. Message-ID: <4i418o$8nu@dawn.mmm.com>
  9. References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM> <VA.00000053.00cdab05@fred> <4i20vi$t6h@news.eunet.ch>
  10. Reply-To: kjhopps@mmm.com
  11. X-Newsreader: TIN [version 1.2 PL2]
  12.  
  13. rop@dial.eunet.ch wrote:
  14. > What about :
  15.  
  16. > T::T(const T&t)
  17. > {
  18. >     *this =t;
  19. > }
  20.  
  21. > That's what I am  always using.
  22.  
  23. As has been posted before, this can cause problems in a class
  24. which must release resources.  Suppose, for example, that T is
  25. a String class which dynamically allocates memory and stores a
  26. pointer to it.
  27.  
  28. If the assignment operator is to allocate new memory for a copy
  29. of the new string, it must either delete the current memory it
  30. holds, or there will be a memory leak.
  31.  
  32. Assuming that the assignment operator deletes its current memory,
  33. the copy constructor above will be problematic because the pointer
  34. is not initialized, and a garbage pointer will be deleted.
  35.  
  36. Calling the assignment operator from the copy constructor can work,
  37. but the members must be initialized first.
  38. --
  39. Kevin J. Hopps, 3M Company     kjhopps@mmm.com
  40. Opinions are my own.  I don't speak for 3M.
  41.     But 3M speaks for me -- I did not write the following line:
  42.  
  43. Opinions expressed herein are my own and may not represent those of 3M.
  44.